﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IAS.WEB.ViewModels;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.Mvc;
using ServiceStack.OrmLite;
using System.Web.Security;

namespace IAS.WEB.Areas.Account.Controllers
{
    public class RegisterController : ServiceStackController
    {
        // GET: Register
        public ActionResult Index()
        {
            Common.NetHelper.SendMail("test", "http://www.baidu.com", "271672848@qq.com");
            return View();
        }

        public ActionResult Register(string userName, string email, string password, string confirmPassword)
        {
            if (ModelState.IsValid)
            {
                if(string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(email))
                {
                    ModelState.AddModelError("", "用户名或注册邮箱不能为空");
                    return View("Index");
                }
                if(string.IsNullOrEmpty(password))
                {
                    ModelState.AddModelError("", "请填写密码");
                    return View("Index");
                }
                if (!password.Equals(confirmPassword))
                {
                    ModelState.AddModelError("", "密码不匹配");
                    return View("Index");
                }
                try
                {
                    using (var regService = ResolveService<RegisterService>())
                    {
                        Register newUser = new ServiceStack.Register() { Email = email, UserName = userName, Password = password };
                        var regRet = regService.Post(newUser) as RegisterResponse;
                        
                        string activeCode = userName + email + password + DateTime.Now.ToString();
                        //默认不激活账户
                        var authRepo = TryResolve<IAuthRepository>();
                       
                        if(null != authRepo)
                        {
                            var existingUser = authRepo.GetUserAuthByUserName(userName) as UserAuth;
                            if (existingUser == null)
                                throw HttpError.NotFound(ErrorMessages.UserNotExists);
                            existingUser.LockedDate = DateTime.Now;
                            activeCode = Common.Commons.CalculateMD5Hash(activeCode);
                            existingUser.RecoveryToken = activeCode;
                            authRepo.SaveUserAuth(existingUser);
                            string url = HttpContext.Request.Url.Host + ":" + HttpContext.Request.Url.Port.ToString();
                            url = this.Server.UrlPathEncode("http://{0}/Account/Register/ActiveAccount?userName={1}&code={2}").Fmt(url, userName, activeCode);
                            // add ASP.NET auth cookie
                            //FormsAuthentication.SetAuthCookie(userName, true); //授权
                            Common.NetHelper.SendMail(null, url, email);
                            return RedirectToAction("ActiveCode");
                        }
                        else
                        {
                            ModelState.AddModelError("", "无法注册，请联系管理员");
                        }
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }
            return View("Index", new RegisterViewModel() { UserName = userName, Email = email }); ;
        }

        public ActionResult ActiveCode()
        {
            return View();
        }

        public ActionResult ActiveAccount(string userName, string code)
        {
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(code))
            {
                ModelState.AddModelError("", "无效激活信息");
                return View();
            }
            var authRepo = TryResolve<IAuthRepository>();
            if(authRepo != null)
            {
               var user = authRepo.GetUserAuthByUserName(userName) as UserAuth;
                if(null == user)
                    throw HttpError.NotFound(ErrorMessages.UserNotExists);
                if(!string.IsNullOrEmpty(user.RecoveryToken) && null != user.LockedDate)
                {
                    if(user.RecoveryToken.Equals(code,StringComparison.OrdinalIgnoreCase))
                    {
                        user.RecoveryToken = null;
                        user.LockedDate = null;
                        authRepo.SaveUserAuth(user);
                    }
                    else
                    {
                        throw HttpError.NotFound("无效激活信息");
                    }
                }
                else
                {
                    throw HttpError.NotFound("无效激活信息");
                }
            }
            return View();
        }

       
    }
}